import 'dart:convert';

import 'package:flustars/flustars.dart';
import 'package:wallet_home/tools/common.dart';

class AddressItem {
  String name;
  String coinType;
  String address;
  // String timeStamp;
  // bool islegal;

  // AddressItem(this.name, this.coinType, this.address, this.timeStamp);
  AddressItem(
    this.name,
    this.coinType,
    this.address,
  );

  bool isSameAddress(AddressItem anotheItem) {
    if (anotheItem.name == this.name && anotheItem.coinType == this.coinType) {
      /// 对比与其他元素，定性其是否为同一个对象
      return true;
    }
    return false;
  }

  /// 校验添加元素的唯一性
  bool islegal() {
    List<AddressItem> tempList = AddressItem.getAddressList();

    /// 没有数据时，即为新增第一条数据时为合法
    if (tempList.length == 0) {
      return true;
    }
    for (var i = 0; i < tempList.length; i++) {
      if (tempList[i].name == this.name &&
          tempList[i].coinType == this.coinType) {
        /// 缓存数据中已有该值时，标记为非法新增
        return false;
      }
    }

    /// 数据默认合法
    return true;
  }

  static String getMicrosecondsTimeStamp() {
    var dateTime = DateTime.now().microsecondsSinceEpoch;
    print(
        'getTimeStamp 毫秒 --- ${DateTime.now().millisecondsSinceEpoch.toString()}');
    print('getTimeStamp 微秒 --- ${dateTime.toString()}');
    return dateTime.toString();
  }

  AddressItem.fromJson(Map<String, dynamic> json) {
    name = json['name'] ?? '';
    coinType = json['coinType'] ?? '';
    address = json['address'] ?? '';
  }

  Map<String, dynamic> toJson() {
    Map<String, dynamic> data = Map<String, dynamic>();
    data['name'] = this.name;
    data['coinType'] = this.coinType;
    data['address'] = this.address;
    return data;
  }

  /// 本地获取之前用户地址库缓存
  static List<AddressItem> getAddressList() {
    List<AddressItem> addressItemList = [];
    String tempItemsListStr =
        SpUtil.getString(Constant.localAddressList, defValue: '[]');
    List tempItemsList = json.decode(tempItemsListStr).toList();
    for (Map<String, dynamic> item in tempItemsList) {
      addressItemList.add(AddressItem.fromJson(item));
    }
    return addressItemList;
  }

  /// 本地存储用户地址库
  static void saveAddressList(List<AddressItem> items) {
    List<Map<String, dynamic>> jsonList = [];
    for (AddressItem item in items) {
      jsonList.add(item.toJson());
    }
    String tempItemsList = json.encode(jsonList).toString();
    SpUtil.putString(Constant.localAddressList, tempItemsList);
  }
}
